package Servlets;

import main.ServerGlobals;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import protocol.HTTPRequest;
import protocol.HTTPResponse;
import protocol.Headers;

public class queue extends Servlet {
	private static final int MESSAGE_UNREAD = 0;
	private static final int MESSAGE_PROCESSING = 2;
	private static final int MESSAGE_READ = 1;

	@Override
	public HTTPResponse process(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		if (!this.isCorrectMethod(httpRequest, Headers.GET)) {
			return new HTTPResponse(Headers.STATUS_405, Headers.HTTP_VERSION,
					new JSONObject(), "", false);
		}
		if (!this.isAuthorized(httpRequest, serverGlobals)) {
			return new HTTPResponse(Headers.STATUS_403, Headers.HTTP_VERSION,
					new JSONObject(), "", false);
		}
		this.fSQLLiteHandler.Query("UPDATE "
				+ WhatsAppConstatnts.TABLE_MESSAGES
				+ " set isRead="
				+ queue.MESSAGE_PROCESSING
				+ " WHERE Target='"
				+ ServerGlobals.getInstance()
						.getSession(this.getSessionId(httpRequest))
						.get(WhatsAppConstatnts.USERNAME).toString()
				+ "' and isRead=" + queue.MESSAGE_UNREAD);
		JSONArray res = this.fSQLLiteHandler
				.Query("select  message, target ,GroupName from "
						+ WhatsAppConstatnts.TABLE_MESSAGES
						+ " Where isRead=2 and Target='"
						+ ServerGlobals.getInstance()
								.getSession(this.getSessionId(httpRequest))
								.get(WhatsAppConstatnts.USERNAME).toString()
						+ "' order by ID ASC");
		this.fSQLLiteHandler.Query("UPDATE "
				+ WhatsAppConstatnts.TABLE_MESSAGES
				+ " set isRead="
				+ queue.MESSAGE_READ
				+ " WHERE Target='"
				+ ServerGlobals.getInstance()
						.getSession(this.getSessionId(httpRequest))
						.get(WhatsAppConstatnts.USERNAME).toString()
				+ "' and isRead=" + queue.MESSAGE_PROCESSING);

		String messages = new String();
		for (int i = 0; i < res.size(); i++) {

			if (null == (((JSONObject) res.get(i))
					.get(WhatsAppConstatnts.GROUP_NAME))) {
				messages += "From: "
						+ ((JSONObject) res.get(i)).get("target").toString()
						+ "\n" + "Message: "
						+ ((JSONObject) res.get(i)).get("message").toString()
						+ "\n";
			} else {
				messages += "From: "
						+ ((JSONObject) res.get(i)).get(
								WhatsAppConstatnts.GROUP_NAME).toString()
						+ "\n" + "Message: "
						+ ((JSONObject) res.get(i)).get("message").toString()
						+ "\n";
			}
		}
		if (res.size() == 0) {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(), WhatsAppConstatnts.NO_NEW_MESSAGES, false);
		} else {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(), messages.substring(0,
							messages.length() - 1), false);
		}
	}

}
